
import mixin from '@/service/mixin';
import Pagination from '@/components/pagination';
import { apiConf } from '@/config';

export default {
    name: 'smsManage-sendManually',
    components: {
        Pagination,
    },
    mixins: [mixin],
    data() {
        return {
            domain:"",
            form: {
                sendProvider: '',
                operator: '',
            },
            formLabelWidth: this.$i18n.locale === 'zhCN' ? '100px' : '120px',
            uploadUrl: apiConf.baseUrl + '/sms/smsSend/importPhoneList',
//                uploadUrl: 'http://192.168.5.94:8075/smsSend/importPhoneList',
            uploadHeader: {
                token: this.$storage.get('user').token,
                Authorization: 'Basic cGluamFtYW5nbzpwaW5qYW1hbmdvMDE4',
//                    'X-LG-CompanyName': this.$storage.get('user').companyName,
//                    'X-LG-Domain': this.$storage.get('user').domain,
            },
            uploadLoading: false,
            uploadLoadSuccess: null,
            uploadLoadFailed: null,
            uploadLoadName: null,
            sendDialog: {
                isVisible: false,
                form: {
                    importUsers: [],
                    messageType: '',
                    msgContent: '',
                    note: '',
                },
                rules: {
                    importUsers: [
                        { required: true, message: this.$t('verify.plsUpload'), trigger: 'change' }
                    ],
                    messageType: [
                        { required: true, message: this.$t('verify.plsChoose'), trigger: 'change' }
                    ],
                    msgContent: [
                        { required: true, message: this.$t('verify.plsInput'), trigger: 'blur' }
                    ],
                    msgHref: [],
                }
            },
            smsWordCount: 140, //每条短信的字数
            rules: {},
            tableData: [],
            messageTypeData: [],
        };
    },
    computed: {
        //根据短信的内容计算需发送的条数
        smsNumber() {
            let msgContentLength = this.sendDialog.form.msgContent.length;
            if(msgContentLength > 0) {
                return Math.ceil(msgContentLength / this.smsWordCount)
            }else {
                return 0
            }
        }
    },
    methods: {
        // 搜索列表数据
        search() {
            this.$refs.form.validate(val => {
                if (val) {
                    this.page.currentPage = 1;
                    this.getTableData();
                }
            });
        },
        // 获取列表数据
        getTableData(page = this.page) {
            const form = this.form;
            const params = {
                sendProvider: form.sendProvider,
                startTime: '',
                endTime: '',
                operator: form.operator,
                pageNo: page.currentPage,
                pageSize: this.page.pageSize
            };
            if (form.registerTime && form.registerTime.length) {
                params.startTime = form.registerTime[0];
                params.endTime = form.registerTime[1];
            }
            this.$api.sms.getSmsBatchRecordByParams(params).then(res => {
                const {status, data, error} = res;
                if ('1' === status && '00000000' === error && data) {
                    this.tableData = data.list;
                    this.setPage({total: data.total,page: page.currentPage}, this.page);
                }
                this.tableMaxHeight = document.body.clientHeight - 190;
            });
        },
        //下载失败表格
        downloadFail(row) {
            const params = {
                recordId: row.id
            };
            const user = this.$storage.get("user");
            const language = this.$storage.getLocal('language');
            params.language = language;
            params.token = user.token;
            const {$apiConf} = this;
            const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.sms.exportFailPhones, []);
            this.$openNewBlank(url);
        },
        sendSMS() {
            this.uploadLoadSuccess = '';
            this.uploadLoadFailed = '';
            this.uploadLoadName = '';
            this.sendDialog.form.importUsers = [];
            if(this.$refs['sendDialog.form']) {
                this.$refs['sendDialog.form'].resetFields();
            }
            this.sendDialog.isVisible = true;
        },
        downloadTemplateExcel() {
            window.location.href = '/phone.xls'
        },
        // 上传前
        beforeUpload(file) {
            let flag = false;
            const arr = file.name.split('.');
            const ext = arr[arr.length - 1];
            if (ext && (ext === 'xls' || ext === 'xlsx' || ext === 'csv')) {
                flag = true;
            }
            if (flag) {
                this.uploadLoading = true;
            } else {
                this.$message.warning(this.$tc('common.onlyExcel'));
            }
            return flag;
        },
        // 取消上传中状态
        closeLoading() {
            this.uploadLoading = false;
        },
        // 上传成功
        uploadSuccess(res, file) {
            const { status, data, msg } = res;
            this.closeLoading();
            if (status === '1') {
                this.uploadLoadName = file.name;
                this.sendDialog.form.importUsers = data;
                this.$message.success(this.$tc('common.importSuccess'));
            } else {
                this.$message.error(msg || this.$tc('common.importFail'));
            }
        },
        sendConfirm() {
            this.$refs['sendDialog.form'].validate(val => {
                if (val) {
                    const form = this.sendDialog.form;
                    const user = this.$storage.get('user');
                    if(form.importUsers.length > 10000) {
                        this.$message.error(this.$tc('common.smsTemplateImportRule', 1, {x: '10000'}));
                        return
                    }
                    const params = {
                        sendProvider: form.messageType,
                        content: form.msgContent,
                        operator: user.username,
                        company: user.companyName,
                        domain: user.domain,
                        phoneSet: form.importUsers,
                        remarks: form.note
                    };
                    this.$api.sms.batchSend(params).then(res => {
                        const {status, error} = res;
                        if ('1' === status && '00000000' === error) {
                            this.$message.success(this.$tc('common.successfulOperation'));
                            this.sendDialog.isVisible = false;
                            this.search();
                        }
                    });
                }
            })
        },
        getMessageType() {
            this.$api.sms.getSmsSendBatchAllProvider({}).then(res => {
                const {status, data, error} = res;
                if ('1' === status && '00000000' === error) {
                    this.messageTypeData = data;
                }
            });
        }
    },
    created() {
        this.getMessageType();
        this.getTableData();
        this.domain = this.$storage.get('user').domain;

    },
};
